<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>java-rmi源码解析 | Eetal&#39;s Blog</title>

  <!-- keywords -->
  

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="欢迎查看Eetal的第二十一篇博客–java-rmi源码解析 相关核心类sun.rmi.server.UnicastServerRefsun.rmi.server.UnicastRefsun.rmi.server.Utilsun.rmi.transport.tcp.TCPEndpointsun.rmi.transport.LiveRefjava.rmi.Namingsun.rmi.registry">
<meta property="og:type" content="article">
<meta property="og:title" content="java-rmi源码解析">
<meta property="og:url" content="http://eetal.gitee.io/blog/2019/06/20/java-rmi源码解析/index.html">
<meta property="og:site_name" content="Eetal&#39;s Blog">
<meta property="og:description" content="欢迎查看Eetal的第二十一篇博客–java-rmi源码解析 相关核心类sun.rmi.server.UnicastServerRefsun.rmi.server.UnicastRefsun.rmi.server.Utilsun.rmi.transport.tcp.TCPEndpointsun.rmi.transport.LiveRefjava.rmi.Namingsun.rmi.registry">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-06-20T08:15:01.501Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java-rmi源码解析">
<meta name="twitter:description" content="欢迎查看Eetal的第二十一篇博客–java-rmi源码解析 相关核心类sun.rmi.server.UnicastServerRefsun.rmi.server.UnicastRefsun.rmi.server.Utilsun.rmi.transport.tcp.TCPEndpointsun.rmi.transport.LiveRefjava.rmi.Namingsun.rmi.registry">
  
    <link rel="alternative" href="/atom.xml" title="Eetal&#39;s Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="http://www.yangyitao.top/FiveChess/resource/ico/favicon.ico">
  
  <link rel="stylesheet" href="/blog/css/style.css">
  
  

  <script src="//cdn.bootcss.com/require.js/2.3.2/require.min.js"></script>
  <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

  
</head>
<body>
  <div id="container">
    <div id="particles-js"></div>
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Eetal</a></h1>
		</hgroup>

		
		<p class="header-subtitle">java coder</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/blog/">Home</a></li>
				        
							<li><a href="/blog/archives">Archives</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="https://github.com/smackgg/hexo-theme-smackdown">smackdown</a>
			        
			        </div>
				</section>
				

				
			</div>
		</div>
	</header>				
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Eetal</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
				<img lazy-src="/blog/images/head.jpg" class="js-avatar">
			</div>
			<hgroup>
			  <h1 class="header-author">Eetal</h1>
			</hgroup>
			
			<p class="header-subtitle">java coder</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/blog/">Home</a></li>
		        
					<li><a href="/blog/archives">Archives</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
				</div>
			</nav>
		</header>				
	</div>
</nav>
      <div class="body-wrap"><article id="post-java-rmi源码解析" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/blog/2019/06/20/java-rmi源码解析/" class="article-date">
  	<time datetime="2019-06-20T07:08:18.101Z" itemprop="datePublished">2019-06-20</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      java-rmi源码解析
      
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
        

        
        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>欢迎查看Eetal的第二十一篇博客–java-rmi源码解析</p>
<h2 id="相关核心类"><a href="#相关核心类" class="headerlink" title="相关核心类"></a>相关核心类</h2><p>sun.rmi.server.UnicastServerRef<br>sun.rmi.server.UnicastRef<br>sun.rmi.server.Util<br>sun.rmi.transport.tcp.TCPEndpoint<br>sun.rmi.transport.LiveRef<br>java.rmi.Naming<br>sun.rmi.registry.RegistryImpl</p>
<h2 id="rmi"><a href="#rmi" class="headerlink" title="rmi"></a>rmi</h2><p>RMI是Java的一组拥护开发分布式应用程序的API。<br>RMI使用Java语言接口定义了远程对象，它集合了Java序列化和Java远程方法协议(Java Remote Method Protocol)。<br>简单地说，这样使原先的程序在同一操作系统的方法调用，变成了不同操作系统之间程序的方法调用，由于J2EE是分布式程序平台，它以RMI机制实现程序组件在不同操作系统之间的通信。<br>比如，一个EJB可以通过RMI调用Web上另一台机器上的EJB远程方法。</p>
<h2 id="简单使用rmi"><a href="#简单使用rmi" class="headerlink" title="简单使用rmi"></a>简单使用rmi</h2><h3 id="要发布的服务接口"><a href="#要发布的服务接口" class="headerlink" title="要发布的服务接口"></a>要发布的服务接口</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public interface HelloService extends Remote&#123;</span><br><span class="line">	public String sayHello() throws RemoteException;</span><br><span class="line">	//要发布的服务类的方法必须都throws RemoteException</span><br><span class="line">	//在Util中，创建代理对象时会checkMethod，存在没有throws RemoteException的则抛出IllegalArgumentException</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>util中的checkMethod<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"> public static Remote createProxy(Class&lt;?&gt; implClass,</span><br><span class="line">                                   RemoteRef clientRef,</span><br><span class="line">                                   boolean forceStubUse)</span><br><span class="line">      throws StubNotFoundException</span><br><span class="line">  &#123;</span><br><span class="line">      .....</span><br><span class="line">      final Class&lt;?&gt;[] interfaces = getRemoteInterfaces(implClass);</span><br><span class="line">      .....</span><br><span class="line">  &#125;</span><br><span class="line">  private static Class&lt;?&gt;[] getRemoteInterfaces(Class&lt;?&gt; remoteClass) &#123;</span><br><span class="line">      ArrayList&lt;Class&lt;?&gt;&gt; list = new ArrayList&lt;&gt;();</span><br><span class="line">      getRemoteInterfaces(list, remoteClass);</span><br><span class="line">      <span class="built_in">return</span> list.toArray(new Class&lt;?&gt;[list.size()]);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  private static void getRemoteInterfaces(ArrayList&lt;Class&lt;?&gt;&gt; list, Class&lt;?&gt; cl) &#123;</span><br><span class="line">.....</span><br><span class="line">      <span class="keyword">for</span> (int i = 0; i &lt; interfaces.length; i++) &#123;</span><br><span class="line">          Class&lt;?&gt; intf = interfaces[i];</span><br><span class="line">          <span class="keyword">if</span> (Remote.class.isAssignableFrom(intf)) &#123;</span><br><span class="line">              <span class="keyword">if</span> (!(list.contains(intf))) &#123;</span><br><span class="line">                  Method[] methods = intf.getMethods();</span><br><span class="line">                  <span class="keyword">for</span> (int j = 0; j &lt; methods.length; j++) &#123;</span><br><span class="line">                      checkMethod(methods[j]);</span><br><span class="line">                  &#125;</span><br><span class="line">                  list.add(intf);</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  private static void checkMethod(Method m) &#123;</span><br><span class="line">      Class&lt;?&gt;[] ex = m.getExceptionTypes();</span><br><span class="line">      <span class="keyword">for</span> (int i = 0; i &lt; ex.length; i++) &#123;</span><br><span class="line">          <span class="keyword">if</span> (ex[i].isAssignableFrom(RemoteException.class))</span><br><span class="line">              <span class="built_in">return</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      throw new IllegalArgumentException(</span><br><span class="line">          <span class="string">"illegal remote method encountered: "</span> + m);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="要发布的服务接口的实现类"><a href="#要发布的服务接口的实现类" class="headerlink" title="要发布的服务接口的实现类"></a>要发布的服务接口的实现类</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public class HelloServiceImpl extends UnicastRemoteObject implements HelloService &#123;</span><br><span class="line">	//需要继承UnicastRemoteObject，因为Remote只是接口，UnicastRemoteObject是Remote的实现类</span><br><span class="line"></span><br><span class="line">	protected HelloServiceImpl() throws RemoteException &#123;</span><br><span class="line">		super();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public String sayHello() throws RemoteException&#123;</span><br><span class="line">		<span class="built_in">return</span> <span class="string">"hello"</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="服务发布端与客户消费端"><a href="#服务发布端与客户消费端" class="headerlink" title="服务发布端与客户消费端"></a>服务发布端与客户消费端</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">public class Server &#123;</span><br><span class="line">	final static String host = <span class="string">"127.0.0.1"</span>;</span><br><span class="line">	final static int port = 8080;</span><br><span class="line">	public static void main(String[] args) throws RemoteException, MalformedURLException &#123;</span><br><span class="line">		HelloService helloService = new HelloServiceImpl();</span><br><span class="line">		LocateRegistry.createRegistry(port);</span><br><span class="line">		Naming.rebind(<span class="string">"rmi://"</span>+host+<span class="string">":"</span>+port+<span class="string">"/hello"</span>, helloService);//不写port默认是1099</span><br><span class="line">		System.out.println(<span class="string">"服务启动..."</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">public class Client &#123;</span><br><span class="line"></span><br><span class="line">	public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException &#123;</span><br><span class="line">		HelloService helloService = (HelloService) Naming.lookup(<span class="string">"rmi://"</span>+Server.host+<span class="string">":"</span>+Server.port+<span class="string">"/hello"</span>);//默认端口1099</span><br><span class="line">		System.out.println(helloService.sayHello());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="追踪源码"><a href="#追踪源码" class="headerlink" title="追踪源码"></a>追踪源码</h2><p>启动服务前，创建服务对象会调用父类无参构造<br>HelloServiceImpl<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">protected HelloServiceImpl() throws RemoteException &#123;</span><br><span class="line">		super();</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>UnicastRemoteObject构造<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">protected UnicastRemoteObject() throws RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       this(0);</span><br><span class="line">   &#125;</span><br><span class="line"> protected UnicastRemoteObject(int port) throws RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       this.port = port;</span><br><span class="line">       exportObject((Remote) this, port);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>在构造中调用了exportObject，将服务暴露出去<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public static Remote exportObject(Remote obj, int port)</span><br><span class="line">       throws RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       <span class="built_in">return</span> exportObject(obj, new UnicastServerRef(port));</span><br><span class="line">   &#125;</span><br><span class="line">private static Remote exportObject(Remote obj, UnicastServerRef sref)</span><br><span class="line">       throws RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       <span class="keyword">if</span> (obj instanceof UnicastRemoteObject) &#123;</span><br><span class="line">           ((UnicastRemoteObject) obj).ref = sref;</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="built_in">return</span> sref.exportObject(obj, null, <span class="literal">false</span>);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>构造UnicastServerRef服务器对象来发布服务<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public UnicastServerRef(int port) &#123;</span><br><span class="line">       super(new LiveRef(port));</span><br><span class="line">       this.filter = null;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>UnicastServerRef调用父类带参构造<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public UnicastRef(LiveRef liveRef) &#123;</span><br><span class="line">       ref = liveRef;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>sref对象发布服务细节<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public Remote exportObject(Remote impl, Object data,</span><br><span class="line">                              boolean permanent)</span><br><span class="line">       throws RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       Class&lt;?&gt; implClass = impl.getClass();</span><br><span class="line">       Remote stub;</span><br><span class="line"></span><br><span class="line">       try &#123;</span><br><span class="line">           stub = Util.createProxy(implClass, getClientRef(), forceStubUse);</span><br><span class="line">       &#125; catch (IllegalArgumentException e) &#123;</span><br><span class="line">           throw new ExportException(</span><br><span class="line">               <span class="string">"remote object implements illegal remote interface"</span>, e);</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">if</span> (stub instanceof RemoteStub) &#123;</span><br><span class="line">           setSkeleton(impl);</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       Target target =</span><br><span class="line">           new Target(impl, this, stub, ref.getObjID(), permanent);</span><br><span class="line">       ref.exportObject(target);</span><br><span class="line">       hashToMethod_Map = hashToMethod_Maps.get(implClass);</span><br><span class="line">       <span class="built_in">return</span> stub;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>创建代理对象，并生成一个可以真正发布的target，调用ref对象（上一步构建以后传递到父类构造函数的LiveRef）发布出去<br>LiveRef细节<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public LiveRef(int port) &#123;</span><br><span class="line">       this((new ObjID()), port);</span><br><span class="line">   &#125;</span><br><span class="line">public LiveRef(ObjID objID, int port) &#123;</span><br><span class="line">       this(objID, TCPEndpoint.getLocalEndpoint(port), <span class="literal">true</span>);</span><br><span class="line">   &#125;</span><br><span class="line">public LiveRef(ObjID objID, Endpoint endpoint, boolean isLocal) &#123;</span><br><span class="line">       ep = endpoint;</span><br><span class="line">       id = objID;</span><br><span class="line">       this.isLocal = isLocal;</span><br><span class="line">   &#125;</span><br><span class="line">public void exportObject(Target target) throws RemoteException &#123;</span><br><span class="line">       ep.exportObject(target);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>TCPEndpoint.getLocalEndpoint<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">public static TCPEndpoint getLocalEndpoint(int port) &#123;</span><br><span class="line">       <span class="built_in">return</span> getLocalEndpoint(port, null, null);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   public static TCPEndpoint getLocalEndpoint(int port,</span><br><span class="line">                                              RMIClientSocketFactory csf,</span><br><span class="line">                                              RMIServerSocketFactory ssf)</span><br><span class="line">   &#123;</span><br><span class="line">       /*</span><br><span class="line">        * Find mapping <span class="keyword">for</span> an endpoint key to the list of <span class="built_in">local</span> unique</span><br><span class="line">        * endpoints <span class="keyword">for</span> this client/server socket factory pair (perhaps</span><br><span class="line">        * null) <span class="keyword">for</span> the specific port.</span><br><span class="line">        */</span><br><span class="line">       TCPEndpoint ep = null;</span><br><span class="line"></span><br><span class="line">       synchronized (localEndpoints) &#123;</span><br><span class="line">           TCPEndpoint endpointKey = new TCPEndpoint(null, port, csf, ssf);</span><br><span class="line">           LinkedList&lt;TCPEndpoint&gt; epList = localEndpoints.get(endpointKey);</span><br><span class="line">           String localHost = resampleLocalHost();</span><br><span class="line"></span><br><span class="line">           <span class="keyword">if</span> (epList == null) &#123;</span><br><span class="line">               /*</span><br><span class="line">                * Create new endpoint list.</span><br><span class="line">                */</span><br><span class="line">               ep = new TCPEndpoint(localHost, port, csf, ssf);</span><br><span class="line">               epList = new LinkedList&lt;TCPEndpoint&gt;();</span><br><span class="line">               epList.add(ep);</span><br><span class="line">               ep.listenPort = port;</span><br><span class="line">               ep.transport = new TCPTransport(epList);</span><br><span class="line">               localEndpoints.put(endpointKey, epList);</span><br><span class="line"></span><br><span class="line">               <span class="keyword">if</span> (TCPTransport.tcpLog.isLoggable(Log.BRIEF)) &#123;</span><br><span class="line">                   TCPTransport.tcpLog.log(Log.BRIEF,</span><br><span class="line">                       <span class="string">"created local endpoint for socket factory "</span> + ssf +</span><br><span class="line">                       <span class="string">" on port "</span> + port);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">               synchronized (epList) &#123;</span><br><span class="line">                   ep = epList.getLast();</span><br><span class="line">                   String lastHost = ep.host;</span><br><span class="line">                   int lastPort =  ep.port;</span><br><span class="line">                   TCPTransport lastTransport = ep.transport;</span><br><span class="line">                   // assert (localHost == null ^ lastHost != null)</span><br><span class="line">                   <span class="keyword">if</span> (localHost != null &amp;&amp; !localHost.equals(lastHost)) &#123;</span><br><span class="line">                       /*</span><br><span class="line">                        * Hostname has been updated; add updated endpoint</span><br><span class="line">                        * to list.</span><br><span class="line">                        */</span><br><span class="line">                       <span class="keyword">if</span> (lastPort != 0) &#123;</span><br><span class="line">                           /*</span><br><span class="line">                            * Remove outdated endpoints only <span class="keyword">if</span> the</span><br><span class="line">                            * port has already been <span class="built_in">set</span> on those endpoints.</span><br><span class="line">                            */</span><br><span class="line">                           epList.clear();</span><br><span class="line">                       &#125;</span><br><span class="line">                       ep = new TCPEndpoint(localHost, lastPort, csf, ssf);</span><br><span class="line">                       ep.listenPort = port;</span><br><span class="line">                       ep.transport = lastTransport;</span><br><span class="line">                       epList.add(ep);</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="built_in">return</span> ep;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>最终获得一个可以发布服务的TCPEndpoint对象，并调用该对象把服务暴露出去</p>
<h2 id="服务注册与拉取源码分析"><a href="#服务注册与拉取源码分析" class="headerlink" title="服务注册与拉取源码分析"></a>服务注册与拉取源码分析</h2><p>注册服务<br>LocateRegistry.createRegistry(port);<br>创建注册中心时，会创建一个RegistryImpl对象<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public static Registry createRegistry(int port) throws RemoteException &#123;</span><br><span class="line">       <span class="built_in">return</span> new RegistryImpl(port);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>RegistryImpl代表注册中心<br>RegistryImpl中使用一个HashTable来注册（bind）服务和查找(lookup)服务<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line">private Hashtable&lt;String, Remote&gt; bindings = new Hashtable&lt;&gt;(101);</span><br><span class="line">public RegistryImpl(int port)</span><br><span class="line">       throws RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       <span class="keyword">if</span> (port == Registry.REGISTRY_PORT &amp;&amp; System.getSecurityManager() != null) &#123;</span><br><span class="line">           try &#123;</span><br><span class="line">               AccessController.doPrivileged(new PrivilegedExceptionAction&lt;Void&gt;() &#123;</span><br><span class="line">                   public Void run() throws RemoteException &#123;</span><br><span class="line">                       LiveRef lref = new LiveRef(id, port);</span><br><span class="line">                       setup(new UnicastServerRef(lref, RegistryImpl::registryFilter));</span><br><span class="line">                       <span class="built_in">return</span> null;</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;, null, new SocketPermission(<span class="string">"localhost:"</span>+port, <span class="string">"listen,accept"</span>));</span><br><span class="line">           &#125; catch (PrivilegedActionException pae) &#123;</span><br><span class="line">               throw (RemoteException)pae.getException();</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">           LiveRef lref = new LiveRef(id, port);</span><br><span class="line">           setup(new UnicastServerRef(lref, RegistryImpl::registryFilter));</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">private void setup(UnicastServerRef uref)</span><br><span class="line">       throws RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       ref = uref;</span><br><span class="line">       uref.exportObject(this, null, <span class="literal">true</span>);</span><br><span class="line">   &#125;</span><br><span class="line">public Remote lookup(String name)</span><br><span class="line">       throws RemoteException, NotBoundException</span><br><span class="line">   &#123;</span><br><span class="line">       synchronized (bindings) &#123;</span><br><span class="line">           Remote obj = bindings.get(name);</span><br><span class="line">           <span class="keyword">if</span> (obj == null)</span><br><span class="line">               throw new NotBoundException(name);</span><br><span class="line">           <span class="built_in">return</span> obj;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   public void <span class="built_in">bind</span>(String name, Remote obj)</span><br><span class="line">       throws RemoteException, AlreadyBoundException, AccessException</span><br><span class="line">   &#123;</span><br><span class="line">       synchronized (bindings) &#123;</span><br><span class="line">           Remote curr = bindings.get(name);</span><br><span class="line">           <span class="keyword">if</span> (curr != null)</span><br><span class="line">               throw new AlreadyBoundException(name);</span><br><span class="line">           bindings.put(name, obj);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">public void unbind(String name)</span><br><span class="line">       throws RemoteException, NotBoundException, AccessException</span><br><span class="line">   &#123;</span><br><span class="line">       synchronized (bindings) &#123;</span><br><span class="line">           Remote obj = bindings.get(name);</span><br><span class="line">           <span class="keyword">if</span> (obj == null)</span><br><span class="line">               throw new NotBoundException(name);</span><br><span class="line">           bindings.remove(name);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   public void rebind(String name, Remote obj)</span><br><span class="line">       throws RemoteException, AccessException</span><br><span class="line">   &#123;</span><br><span class="line">       bindings.put(name, obj);</span><br><span class="line">   &#125;</span><br><span class="line">.....</span><br></pre></td></tr></table></figure></p>
<p>最终和服务端暴露服务类似，会把RegistryImpl对象暴露出去</p>
<p>当服务提供方调用Naming.rebind(“rmi://“+host+”:”+port+”/hello”, helloService);注册服务时<br>会先根据端口获取到暴露的注册中心对象RegistryImpl，然后调用其方法注册<br>对应的客户端获取服务的过程也是类似(HelloService) Naming.lookup(“rmi://“+Server.host+”:”+Server.port+”/hello”);<br>会先根据端口获取到暴露的注册中心对象RegistryImpl，然后调用其方法获取<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">public static void rebind(String name, Remote obj)</span><br><span class="line">       throws RemoteException, java.net.MalformedURLException</span><br><span class="line">   &#123;</span><br><span class="line">       ParsedNamingURL parsed = parseURL(name);</span><br><span class="line">       Registry registry = getRegistry(parsed);</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span> (obj == null)</span><br><span class="line">           throw new NullPointerException(<span class="string">"cannot bind to null"</span>);</span><br><span class="line"></span><br><span class="line">       registry.rebind(parsed.name, obj);</span><br><span class="line">   &#125;</span><br><span class="line">public static Remote lookup(String name)</span><br><span class="line">       throws NotBoundException,</span><br><span class="line">           java.net.MalformedURLException,</span><br><span class="line">           RemoteException</span><br><span class="line">   &#123;</span><br><span class="line">       ParsedNamingURL parsed = parseURL(name);</span><br><span class="line">       Registry registry = getRegistry(parsed);</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span> (parsed.name == null)</span><br><span class="line">           <span class="built_in">return</span> registry;</span><br><span class="line">       <span class="built_in">return</span> registry.lookup(parsed.name);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="更多精彩内容"><a href="#更多精彩内容" class="headerlink" title="更多精彩内容"></a>更多精彩内容</h3><h3 id="请移步"><a href="#请移步" class="headerlink" title="请移步"></a>请移步</h3><p>个人主页: <a href="http://yangyitao.top" target="_blank" rel="noopener">yangyitao.top</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/blog/2019/07/08/MBean与JMX/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">&lt;</strong>
      <div class="article-nav-title">
        
          MBean与JMX
        
      </div>
    </a>
  
  
    <a href="/blog/2019/06/05/springCloud的LoadBalance源码分析/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">SpringCloud的LoadBalance源码分析</div>
      <strong class="article-nav-caption">&gt;</strong>
    </a>
  
</nav>

  
</article>


<div class="ds-share share" data-thread-key="java-rmi源码解析" data-title="java-rmi源码解析" data-url="http://eetal.gitee.io/blog/blog/2019/06/20/java-rmi源码解析/"  data-images="/blog/images/head.jpg" data-content="java-rmi源码解析">
    <div class="ds-share-inline">
      <ul  class="ds-share-icons-16">
      	<li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
        <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
        <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
        <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
        <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>
      </ul>
      <div class="ds-share-icons-more">
      </div>
    </div>
 </div>
 





</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
      <div class="footer-left">
        &copy; 2019 Eetal
      </div>
        <div class="footer-right">
          <a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/smackgg/hexo-theme-smackdown" target="_blank">Smackdown</a>
        </div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/blog/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="/blog/js/main.js"></script>



<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.7.0/MathJax.js"></script>


  </div>
</body>
</html>